import { fetcher } from '@/src/utils/fetcher'
import Paginator from '../../components/paginator'
import dayjs from 'dayjs'
import { cookies } from 'next/headers'
import Article from './components/article'
import { objectToQueryString } from '@/src/utils/object-to-query-string'
import AnchorTitle from '../../components/anchor-title'
import FilterPC from './components/filter-pc'
import FilterMobile from './components/filter-mobile'
import { getTranslations } from 'next-intl/server'

interface PageProps {
  searchParams: {
    page?: string
    category?: string
  }
}

const Page: React.FC<PageProps> = async (props) => {
  const { searchParams } = props
  const t = await getTranslations('news')
  const cookieStore = cookies()
  const categories = await fetcher<NewsCategory[]>(
    '/api/index/znewsClassification',
    { cookieStore }
  )
  const categoryId = searchParams.category || categories[0].id.toString()
  const page = searchParams.page || '1'
  const newsQuery = {
    classificationid: categoryId,
    page: page,
  }
  const news = (await fetcher<WithPaginator<News>>(
    `/api/index/newsList?${objectToQueryString(newsQuery)}`,
    { cookieStore }
  )) || { list: [], p: 0, total: 0 }

  return (
    <>
      <div
        id='news'
        className='h-[1.875rem] lg:h-[2.1875rem] 2xl:h-[3.28125rem]'
      />
      {/* 新闻 */}
      <AnchorTitle title={t('news')}>
        <FilterPC selected={categoryId} categories={categories} />
      </AnchorTitle>
      <div className='h-[0.9375rem] lg:hidden' />
      <FilterMobile selected={categoryId} categories={categories} />
      <div className='h-4 lg:h-2 2xl:h-3' />
      {/* 列表 */}
      <div className='flex flex-col'>
        {news.list.map((item) => {
          return (
            <Article
              key={item.id}
              id={item.id}
              picture={item.image}
              title={item.title}
              desc={item.con}
              createdAt={dayjs
                .unix(Number(item.createtime))
                .format('DD MMM YYYY')}
            />
          )
        })}
      </div>
      <div className='h-[1.875rem] lg:h-[3.1875rem] 2xl:h-[4.78125rem]' />
      <Paginator
        initialPage={Number(searchParams.page) || 1}
        total={Math.ceil(news.total / news.p)}
      />
      <div className='h-[2.34375rem] lg:h-[3.0625rem] 2xl:h-[4.59375rem]' />
    </>
  )
}

export default Page
